<template>
  <div class="custom-wang-editor">
    <!-- 工具栏 -->
    <Toolbar :editor="editorRef" :defaultConfig="mergedToolbarConfig" mode="default" />

    <!-- 编辑器 -->
    <Editor
      :defaultConfig="mergedEditorConfig"
      v-model="content"
      @onCreated="handleEditorCreated"
      @onChange="(e) => $emit('update:modelValue', content)"
      class="custom-editor" />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/common/uploadByQiNiuYun'
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  editorConfig: {
    type: Object,
    default: () => ({})
  },
  toolbarConfig: {
    type: Object,
    default: () => ({})
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
const editorRef = shallowRef()
const content = ref(props.modelValue)

const mergedEditorConfig = computed(() => {
  return {
    // placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        fieldName: 'file',
        maxFileSize: 5 * 1024 * 1024, // 100M
        server: uploadUrl,
        // 自定义插入图片
        customInsert(res, insertFn) {
          // res 即服务端的返回结果
          insertFn(res.data, '', '')
        }
      },
      uploadVideo: {
        fieldName: 'file',
        maxFileSize: 100 * 1024 * 1024, // 1M
        server: uploadUrl,
        customInsert(res, insertFn) {
          // res 即服务端的返回结果
          insertFn(res.data, '')
        }
      }
    },
    ...props.editorConfig
  }
})

const mergedToolbarConfig = computed(() => {
  return {
    excludeKeys: ['insertLink', 'codeBlock', 'todo', 'fullScreen'], // 排除菜单
    ...props.toolbarConfig
  }
})

watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue !== content.value) {
      content.value = newValue
    }
  },
  { immediate: true }
)

watch(
  () => props.disabled,
  (newDisabled) => {
    if (editorRef.value) {
      if (newDisabled) {
        editorRef.value.disable() // 禁用编辑器
      } else {
        editorRef.value.enable() // 启用编辑器
      }
    }
  },
  { immediate: true }
)

function handleEditorCreated(editor) {
  editorRef.value = editor

  // 根据初始化的 disabled 值控制编辑器状态
  console.log('禁用状态', props.disabled, editor)
  if (props.disabled) {
    editorRef.value.disable() // 禁用编辑器
  } else {
    editorRef.value.enable() // 启用编辑器
  }
}

onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy()
    editorRef.value = null
  }
})
</script>
<style lang="scss" scoped>
.custom-wang-editor {
  border: 1px solid #ccc;
  .custom-editor {
    min-height: 300px;
  }
}
</style>
<style lang="scss">

@for $i from 1 through 20 {
  #w-e-textarea-#{$i} {
    min-height: 300px !important;
  }
}
</style>
